package com.soyea.controller;

import com.soyea.dto.WxUserDTO;
import com.soyea.entity.User;
import com.soyea.exception.BizException;
import com.soyea.service.WxUserService;
import com.soyea.vo.ResultEnum;
import com.soyea.vo.ResultVO;
import javafx.scene.control.ButtonType;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.menu.WxMenu;
import me.chanjar.weixin.common.bean.menu.WxMenuButton;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * 抽奖 Controller
 * Created by skh on 2018/1/18
 */
@RestController
@RequestMapping("/wechat")
@Slf4j
public class WechatController {

	@Autowired
	private WxMpService wxMpService;

	@Autowired
	private WxUserService wxUserService;

	//微信认证
//	@RequestMapping("/auth")
//	public String authGet(@RequestParam(name = "signature", required = false) String signature,
//						  @RequestParam(name = "timestamp", required = false) String timestamp,
//						  @RequestParam(name = "nonce", required = false) String nonce,
//						  @RequestParam(name = "echostr", required = false) String echostr) {
//
//		try {
//			log.info("\n接收到来自微信服务器的认证消息：[{}, {}, {}, {}]", signature, timestamp, nonce, echostr);
//
//			if (StringUtils.isAnyBlank(signature, timestamp, nonce, echostr)) {
//				throw new IllegalArgumentException("请求参数非法，请核实!");
//			}
//
//			if (wxMpService.checkSignature(timestamp, nonce, signature)) {
//				log.info("微信认证通过");
//				return echostr;
//			}
//		} catch (Exception e) {
//			log.error("微信认证失败", e);
//		}
//
//		return "非法请求";
//	}

	//自定义菜单
	@RequestMapping("/createMenu")
	public ResultVO createMenu() {
		WxMenu wxMenu = new WxMenu();

		List<WxMenuButton> buttonList = new ArrayList<>();
		WxMenuButton button = new WxMenuButton();
		button.setName("年会登记");
		button.setType("view");
		//构建url String redirectURI, String scope, String state
		String redirectURI="http://dev.core.ren/oauth";
		String url = wxMpService.oauth2buildAuthorizationUrl(redirectURI, WxConsts.OAuth2Scope.SNSAPI_BASE, "123");
		button.setUrl(url);

		buttonList.add(button);
		wxMenu.setButtons(buttonList);

		try {
			wxMpService.getMenuService().menuCreate(wxMenu);
		} catch (WxErrorException e) {
			log.error("自定义菜单出错",e);
			return ResultVO.fail(ResultEnum.MENU_CREATE_ERROR.getCode(),ResultEnum.MENU_CREATE_ERROR.getMessage());
		}
		log.info("自定义菜单成功,菜单={}",wxMenu);

		return ResultVO.success();
	}


	/**
	 * 用户登记
	 * //openId=o28mO0oSucwqWyl8gqYMFgOzl1w4
	 */
	@PostMapping("/regist")
	public ResultVO regist(@Valid WxUserDTO userDTO, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			throw new BizException(ResultEnum.PARAM_ERROR.getCode(),bindingResult.getFieldError().getDefaultMessage());
		}
		wxUserService.save(userDTO);
		return ResultVO.success();
	}

	/**
	 * 前端轮询获取队列中用户信息
	 *
	 * @return
	 */
	@RequestMapping("/pollUser")
	public ResultVO pollUser() {
		User user = wxUserService.pollUser();
		return ResultVO.success(user);
	}

	//获取用户列表
	@RequestMapping("/getUserList")
	public ResultVO getUserList() {
		List<User> userList = wxUserService.selectUserList();
		return ResultVO.success(userList);
	}


	//抽奖,返回中奖用户
	@RequestMapping("/draw")
	public ResultVO draw(Integer prizeStatus) {
		User user = wxUserService.draw(prizeStatus);
		return ResultVO.success(user);
	}

	//返回中奖人数
	@RequestMapping("/countDraw")
	public ResultVO countDrawPeople(Integer prizeStatus) {
		int count = wxUserService.countDrawPeople(prizeStatus);
		return ResultVO.success(count);
	}

	//获取中奖用户列表
	@RequestMapping("/getPrizeUserList")
	public ResultVO getPrizeUserList(Integer prizeStatus) {
		List<User> userList = wxUserService.getPrizeUserList(prizeStatus);
		return ResultVO.success(userList);
	}


	//根据openid删除用户
	@RequestMapping("/delete")
	public ResultVO deleteUserByOpenid(String openid) {
		wxUserService.deleteUserByOpenid(openid);
		return ResultVO.success();
	}

	//将所有中奖用户还原为未中奖用户
	@RequestMapping("/restoreUsersToNoPrize")
	public ResultVO restoreUsersToNoPrize() {
		wxUserService.restoreUsersToNoPrize();
		return ResultVO.success();
	}

}
